package org.doubango.ngn.h264

import org.doubango.ngn.media.NgnProxyVideoProducer
import com.evendai.loglibrary.Timber
import java.util.concurrent.LinkedBlockingDeque

@Suppress("SpellCheckingInspection")
class H264DoubangoSenderThread(producer: NgnProxyVideoProducer) : Thread(TAG) {
    private val mBlockingDeque = LinkedBlockingDeque<ByteArray>(5)
    private val mVideoSender = H264DoubangoSender(producer)
    private var frameLossCount: Int = 0

    fun addH264Datas(datas: ByteArray) {
        val offer = mBlockingDeque.offer(datas)
        if (!offer) {
            Timber.i("${TAG}发送H264数据时丢帧：${++frameLossCount}帧")
        }
    }

    override fun run() {
        try {
            while (!isInterrupted) {
                mVideoSender.sendH264Datas(mBlockingDeque.take())
            }
        } catch (e: InterruptedException) {
            Timber.w("别慌，线程是正常中断的，线程名称 = ${Thread.currentThread().name}")
        } catch (e: Exception) {
            Timber.e(e,"发送H264数据时出现异常")
        }

    }

    fun close() {
        interrupt()
        mVideoSender.close()
    }

    companion object {
        private val TAG = H264DoubangoSenderThread::class.java.simpleName
    }
}